//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using OpenLS.Spreadsheet.Expressions;

namespace OpenLS.Spreadsheet.Formats.Biff.Tokens
{
    internal class NameToken : FormulaToken
    {
        private readonly AccessorType _type;

        public NameToken(AccessorType type)
        {
            _type = type;
        }

        public NameToken(AccessorType type, uint nameIndex): this(type)
        {
            NameIndex = nameIndex;
        }

        private uint _ni = 0xFFFFFFFF;
        uint NameIndex
        {
            get
            {

                Contract.Ensures(Contract.Result<uint>() > 0);
                return _ni;

            }
            set
            {
                Contract.Requires(value > 0);
                _ni = value;
            }
        }

        public override ushort GetLength(FormulaReadContextType formulaReadContextType)
        {
            return 4;
        }


        internal override void ReadContent(FormulaReadContext context)
        {
            NameIndex = context.ReadUInt32();
            //\\ context.ReadUInt16();
        }
        public override void WriteContent(FormulaWriteContext context)
        {
            context.WriteUInt32(NameIndex);

        }

        public override FormulaTokenId TokenId
        {
            get {
                switch (_type)
                {
                        case AccessorType.Array:
                        return FormulaTokenId.NameA;
                        case AccessorType.Reference:
                        return FormulaTokenId.Name;
                        case AccessorType.Value:
                        return FormulaTokenId.NameV;
                    default: throw new NotSupportedException();
                } }
        }

        internal override Expression GetExpression(FormulaEvaluationContext context)
        {
            var n = GetDefinedName(context.WorkbookContext);
            if (context.Target == null)
                return new NameExpression(context.Workbook, n.Name);
                return new NameExpression(context.Target.Worksheet, n.Name);
        }
        public DefinedName GetDefinedName (BiffReaderWorkbookContext context)
        {
            return context.GetDefinedName((int) (NameIndex - 1));
            //return context.Workbook.DefinedNames[(int) (NameIndex- 1)];
        }
    }
}